<template>
  <div id="materialEdit">
		<view class="nav-box">
			<view class="nav-box-text">
				<image src="@/static/img/home/person.png" class="person"></image>
				<view class="welcome">
					<view><text>姓名：{{ userInfo.nickName }}（取样人员）</text></view>
					<view><text>单位：{{ userInfo.dept.deptName }}</text></view>
				</view>
			</view>
		</view>
		<view class="uni-list">
			<uni-forms ref="form" label-width="105" :modelValue="formData" :rules="rules">
				<uni-forms-item label="原材料" name="materialId" required>
					<picker @change="pickerChange" :value="materialIndex" :range="materialOptions" range-key="name">
						<view class="uni-input">{{ materialOptions.length>0?materialOptions[materialIndex].name:'请选择' }}</view>
					</picker>
				</uni-forms-item>
				<uni-forms-item 
					v-for="(item, index) in formList" 
					:label="item.name" 
					:required="item.required"
					:name="item.code"
				>
					<uni-easyinput 
						v-model="formData[item.code]" 
						:inputBorder="false" 
						:maxlength="100"
						placeholder="请输入" 
						v-if="item.inputType == 'INPUT'"
					/>
					<ccPicker 
						v-model="formData[item.code]"
						:range="item.options" 
						k="value" 
						v="key" 
						class="picker"
						v-if="item.inputType == 'SELECT'"
					></ccPicker>
					<uni-easyinput
						v-model="formData[item.code]" 
						:inputBorder="false" 
						style="display: none;"
						v-if="item.inputType == 'SELECT'"
					/>
					<uni-datetime-picker 
						type="date" 
						v-model="formData[item.code]" 
						:border="false"
						v-if="item.inputType == 'DATE'"
					/>
				</uni-forms-item>
			</uni-forms>
		</view>
		<view style="height: 60px;"></view>
		<view class="bottom-nav">
			<button type="primary" :loading="loading" class="btn" @click="save()">上传</button>
		</view>
  </div>
</template>

<script>
import { save, getFormField, getOptions } from '@/api/sample/index'
import ccPicker from "@/components/cc-picker/cc-picker.vue"
import { decrypt } from '@/common/jsencrpty.js'
	
export default {
  data() {
    return {
			// 是否同步数据
			networkFlag: false,
			// 原材料选择
			materialOptions: [],
			materialIndex: 0,
			// 用户信息
			userInfo: {},
			// 取样信息
			sampleInfo: {},
			// 防止重复提交
      loading: false,
			// 表单list
			formList: [],
			formData: {
				materialId: '',
				materialName: ''
			},
			rules: {
				materialId: {
					rules: [{required: true, errorMessage: '请选择原材料'}]
				},
				 formList: [] // 确保 formList 初始化
			}
    }
  },
	components: { ccPicker },
  onLoad(param) {
		 this.networkFlag = param.flag
  this.userInfo = uni.getStorageSync('userInfo') || {}; // 确保 userInfo 不是 undefined
  this.userInfo.dept = this.userInfo.dept || { deptName: '' }; // 确保 dept 存在
  this.userInfo.nickName = decrypt(this.userInfo.nickName || ''); // 防止 nickName 未定义
  this.sampleInfo = uni.getStorageSync('sampleInfo') || {};
  this.getMaterialOptions()
  this.getFormField(this.sampleInfo.typeId)
  },
  onReady() {
    
  },
  methods: {
		// 获取原材料数据
		getMaterialOptions() {
			let id = uni.getStorageSync('projectInfo').id
			console.log(id,'jiance')
			let data = {
				projectId:id
			}
			getOptions(data).then(res=>{
				res.rows.forEach((item, index)=>{
					// item.name = `${item.name}(${item.batch})`
					item.value = item.id
				})
				res.rows.unshift({
					id: '',
					value: '',
					name: '请选择'
				})
				this.materialOptions = res.rows
			})
		},
		// 原材料选中
		pickerChange(e) {
			this.materialIndex = e.detail.value
			let obj = this.materialOptions.find((item, index)=>{ return index === e.detail.value })
			this.formData.materialId = obj.value
			this.formData.materialName = obj.name=='请选择'?'':obj.name
			this.formList.forEach(item=>{
				for (let key in obj) {
					if((item.inputType != 'SELECT')&&(item.inputType != 'DATE')){
						if(item.materialKey == key){
							this.formData[item.code] = obj[key]
						}
					}
				}
			})
		},
		// 获取表单信息
		getFormField(typeId) {
			getFormField(typeId).then(res=>{
				res.data.forEach(item=>{
					if (item.inputType == 'DATE') {
						this.formData[item.code] = ''
					}
					if (item.defaultValue) {
						this.formData[item.code] = item.defaultValue
					}
					if (item.validateRuleList) {
						this.rules[item.code] = {
							'rules': Array.isArray(item.validateRuleList) ? item.validateRuleList : [] // 确保是数组
						}
					}
				})
				this.formList = res.data
				console.log(this.formList)
			})
		},
		// 保存取样信息
    save() {
			this.$refs['form'].validate().then(res=>{
				this.sampleInfo.materialId = this.formData.materialId
				this.sampleInfo.materialName = this.formData.materialName
				this.formList.forEach(item=>{
					if (item.inputType == 'SELECT') {
						item.options.forEach(child=>{
							if (child.key == this.formData[item.code]) {
								item.value = child.value
							}
						})
					} else {
						item.value = this.formData[item.code]
					}
				})
				this.sampleInfo.formValues = this.formList
				this.loading = true
				save(this.sampleInfo).then(res=>{
					this.loading = false
					if (res.code == 200) {
						if (this.networkFlag) {
							uni.removeStorageSync('networkData')
						}
						uni.showToast({
							title: "上传成功",
							duration: 1500
						})
						uni.navigateTo({
							url: '/pages/menu/index'
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			});
		}
  }
}
</script>
<style lang="scss" scoped>
	#materialEdit {
		min-height: 100vh;
		background-color: #fafafa;
		
		.nav-box {
			width: 100vw;
			height: 160px;
			margin-top: -44px;
			padding: 56px 20px 56px 20px;
			background-image: url(../../static/img/home/head-bg.png);
			
			.nav-box-text {
				height: 50px;
				display: flex;
				align-items: center;
				
				.person {
					width: 48px;
					height: 48px;
				}
				.welcome {
					color: #333;
					font-size: 32rpx;
					margin-left: 40rpx;
				}
			}
		}
		
		.uni-list {
			background-color: #fff;
			margin: -30px 20px 0 20px;
			box-shadow: 0px 0px 5px 1px rgba(0, 0, 0, .1);
			
			/deep/ .uni-forms-item__inner {
				padding: 0 10px;
				border-bottom: 1rpx solid #bfbfbf;
			}
			/deep/ .uni-error-message {
				right: 0;
				left: auto;
				margin-right: 5px;
			}
			/deep/ .uni-date__x-input {
				height: 36px;
				line-height: 36px;
			}
			/deep/ .uni-group {
				margin-top: 0 !important;
			}
			/deep/ .uni-input {
				display: flex;
				font-size: 14px;
				min-height: 36px;
				padding-left: 12px;
				align-items: center;
			}
			.picker {
				height: 36px;
				line-height: 36px;
				padding-left: 10px;
				
				/deep/ uni-view {
					height: 36px;
					line-height: 36px;
				}
			}
			.uni-forms-item {
				
				&:last-child {
					/deep/ .uni-forms-item__inner {
						border-bottom: 0;
					}
				}
			}
		}
		
		.bottom-nav {
			left: 0;
			bottom: 0;
			width: 100vw;
			height: 50px;
			padding: 10px;
			position: fixed;
			background-color: #fff;
			box-shadow: 0px 0px 5px 1px rgba(0, 0, 0, .1);
		}
	}
</style>
